import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

interface Waybill {
  id: number;
  team: string;
  warehouseName: string;
  waybillNumber: string;
  outboundOrderNumber: string;
  creationTime: string;
  skuType: string;
  skuQuantity: string;
  weight: number;
  length: number;
  width: number;
  height: number;
  recipient: string;
  recipientPhoneNumber: string;
  attachment: string;
  states: string;
}

interface ApiPaging<T> {
  items: T[];
  totalCount: number;
  totalPage: number;
}

const ShowPendingShipmentWaybills = () => {
  const [data, setData] = useState<Waybill[]>([]);
  const [loading, setLoading] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(3);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState("");
  const [states, setStates] = useState("");
  const navigate = useNavigate();
  // 这里可扩展仓库、团队筛选

  const fetchData = async () => {
    setLoading(true);
    const paramsObj: any = {
      PageIndex: String(pageIndex),
      PageSize: String(pageSize),
    };
    if (search) paramsObj.OutboundOrderNumber = search;
    if (states) paramsObj.States = states;
    const params = new URLSearchParams(paramsObj);
  
    try {
      const res = await fetch(`http://localhost:5017/api/PendingShipmentWaybills/ShowPendingShipmentWaybills?${params}`);
      const json: ApiPaging<Waybill> = await res.json();
      setData(json.items || []);
      setTotal(json.totalCount || 0);
    } catch (e) {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line
  }, [pageIndex, pageSize]);

  const handleSearch = () => {
    setPageIndex(1);
    fetchData();
  };

  const handleReset = () => {
    setSearch("");
    setStates("");
    setPageIndex(1);
    fetchData();
  };

  return (
    <div style={{ padding: 20, background: "#fafbfc", minHeight: "100vh" }}>
      {/* 新增按钮 */}
      <div style={{ marginBottom: 16, display: "flex", justifyContent: "flex-end" }}>
        <button
          style={{ padding: "8px 20px", background: "#1890ff", color: "#fff", border: "none", borderRadius: 4, fontSize: 16, cursor: "pointer" }}
          onClick={() => navigate("/Layout/CreatePendingShipmentWaybills")}
        >
          新增
        </button>
      </div>
      {/* 筛选栏 */}
      <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
        <input
          placeholder="发货单号/转运单号"
          style={{ padding: 6, width: 180 }}
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
        <button onClick={handleSearch} style={{ padding: "6px 16px", background: "#00b388", color: "#fff", border: "none", borderRadius: 4 }}>搜索</button>
        <button onClick={handleReset} style={{ padding: "6px 16px", background: "#eee", border: "none", borderRadius: 4 }}>重置</button>
      </div>

      {/* 表格 */}
      <table style={{ width: "100%", borderCollapse: "collapse", background: "#fff" }}>
        <thead>
          <tr style={{ background: "#f5f7fa" }}>
            <th style={thStyle}>序号</th>
            <th style={thStyle}>团队</th>
            <th style={thStyle}>仓库名称</th>
            <th style={thStyle}>运单号</th>
            <th style={thStyle}>出库单号</th>
            <th style={thStyle}>创建时间</th>
            <th style={thStyle}>SKU种类</th>
            <th style={thStyle}>SKU数量</th>
            <th style={thStyle}>重量(KG)</th>
            <th style={thStyle}>长(CM)</th>
            <th style={thStyle}>宽(CM)</th>
            <th style={thStyle}>高(CM)</th>
            <th style={thStyle}>收件人</th>
            <th style={thStyle}>收件电话</th>
            <th style={thStyle}>附件</th>
            <th style={thStyle}>状态</th>
            <th style={thStyle}>操作</th>
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr><td colSpan={17} style={{ textAlign: "center", padding: 20 }}>加载中...</td></tr>
          ) : data.length === 0 ? (
            <tr><td colSpan={17} style={{ textAlign: "center", padding: 20 }}>暂无数据</td></tr>
          ) : data.map((row, idx) => (
            <tr key={row.id} style={{ textAlign: "center", borderBottom: "1px solid #eee" }}>
              <td style={tdStyle}>{(pageIndex - 1) * pageSize + idx + 1}</td>
              <td style={tdStyle}>{row.team}</td>
              <td style={tdStyle}>{row.warehouseName}</td>
              <td style={tdStyle}>{row.waybillNumber}</td>
              <td style={tdStyle}>{row.outboundOrderNumber}</td>
              <td style={tdStyle}>{row.creationTime}</td>
              <td style={tdStyle}><span style={badgeGreen}>{row.skuType}</span></td>
              <td style={tdStyle}><span style={badgeOrange}>{row.skuQuantity}</span></td>
              <td style={tdStyle}>{row.weight}</td>
              <td style={tdStyle}>{row.length}</td>
              <td style={tdStyle}>{row.width}</td>
              <td style={tdStyle}>{row.height}</td>
              <td style={tdStyle}>{row.recipient}</td>
              <td style={tdStyle}>{row.recipientPhoneNumber}</td>
              <td style={tdStyle}>{row.attachment}</td>
              <td style={tdStyle}>{row.states}</td>
              <td style={tdStyle}>
                <button 
                  style={btnEdit}
                  onClick={() => navigate(`/Layout/UpdatePendingShipmentWaybills/${row.id}`)}
                >
                  修改
                </button>
                <button style={btnDetail}>详情</button>
                <button style={btnShip}>发货</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {/* 分页 */}
      <div style={{ marginTop: 16, textAlign: "right" }}>
        <button
          onClick={() => setPageIndex(p => Math.max(1, p - 1))}
          disabled={pageIndex === 1}
          style={{ marginRight: 8, padding: "4px 12px", borderRadius: 4, border: "1px solid #eee", background: pageIndex === 1 ? "#f5f5f5" : "#fff", cursor: pageIndex === 1 ? "not-allowed" : "pointer" }}
        >上一页</button>
        <span>第 {pageIndex} / {Math.max(1, Math.ceil(total / pageSize))} 页</span>
        <button
          onClick={() => setPageIndex(p => p + 1)}
          disabled={pageIndex >= Math.ceil(total / pageSize)}
          style={{ marginLeft: 8, padding: "4px 12px", borderRadius: 4, border: "1px solid #eee", background: pageIndex >= Math.ceil(total / pageSize) ? "#f5f5f5" : "#fff", cursor: pageIndex >= Math.ceil(total / pageSize) ? "not-allowed" : "pointer" }}
        >下一页</button>
      </div>
    </div>
  );
};

// 样式
const thStyle = { padding: 8, border: "1px solid #eee", fontWeight: 600 };
const tdStyle = { padding: 8, border: "1px solid #eee" };
const badgeGreen = { background: "#00b388", color: "#fff", borderRadius: 4, padding: "2px 8px", fontSize: 12 };
const badgeOrange = { background: "#ffa940", color: "#fff", borderRadius: 4, padding: "2px 8px", fontSize: 12 };
const btnEdit = { background: "#13c2c2", color: "#fff", border: "none", borderRadius: 4, padding: "4px 10px", marginRight: 4, cursor: "pointer" };
const btnDetail = { background: "#1890ff", color: "#fff", border: "none", borderRadius: 4, padding: "4px 10px", marginRight: 4, cursor: "pointer" };
const btnShip = { background: "#faad14", color: "#fff", border: "none", borderRadius: 4, padding: "4px 10px", cursor: "pointer" };

export default ShowPendingShipmentWaybills;